package com.sita.tboard.roadtrust.discovery;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.OnClickListener;
import com.sita.bike.R;
import com.sita.bike.model.EaseUser2;
import com.sita.bike.persistence.RtBlacklistEntity;
import com.sita.bike.persistence.RtResourceEntityDao;
import com.sita.bike.persistence.TrendMember;
import com.sita.bike.rest.RestClient;
import com.sita.bike.rest.model.request.RtBlacklistRequest;
import com.sita.bike.rest.model.request.RtDelResourceRequest;
import com.sita.bike.rest.model.response.RtBlacklistResponse;
import com.sita.bike.rest.model.response.RtDelResourceResponse;
import com.sita.bike.support.GlobalContext;
import com.sita.bike.ui.activity.roadtrust.VideoPlayActivity;
import com.sita.bike.utils.AccountUtils;
import com.sita.bike.utils.LogUtils;
import com.sita.bike.utils.PersistUtils;
import com.sita.bike.utils.ShareUtils;
import com.sita.friend.FriendHelper;
import com.sita.tboard.global.LocalConstants;
import com.sita.tboard.roadtrust.detail.RtNoteListActivity;
import com.sita.tboard.roadtrust.event.RtResourceRefreshEvent;
import com.sita.tboard.roadtrust.gridimage.RtResourceGalleryAdapter;
import com.sita.tboard.roadtrust.helper.RtGeneralHelper;
import com.sita.tboard.ui.tools.L;
import com.sita.tboard.usermgmt.helper.UserNetworkHelper;
import com.sita.tboard.util.DateUtils;
import com.sita.tboard.view.CursorRecyclerAdapter;
import com.sita.tboard.view.ImageModel;
import com.sita.tboard.view.NineGridlayout;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import de.hdodenhof.circleimageview.CircleImageView;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by xiaodong on 16/3/22.
 */
public class RtResourceListAdapter extends CursorRecyclerAdapter<RtResourceListAdapter.ViewHolder> {

    private final String TAG = RtResourceListAdapter.class.getSimpleName();
    private Context mContext;

    public RtResourceListAdapter(Context context, Cursor cursor) {
        super(cursor);
        mContext = context;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_rt_resource_in_list, parent, false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolderCursor(ViewHolder holder, Cursor cursor) {
        Long resId = cursor.getLong(cursor.getColumnIndex(RtResourceEntityDao.Properties.Id.columnName));
        final String resourceId = String.valueOf(resId);
        final String accountId = cursor.getString(cursor.getColumnIndex(RtResourceEntityDao.Properties.AccountId.columnName));

        final String title = cursor.getString(cursor.getColumnIndex(RtResourceEntityDao.Properties.Title.columnName));
        long createDate = cursor.getLong(cursor.getColumnIndex(RtResourceEntityDao.Properties.CreateDate.columnName));
        String shortVideo = cursor.getString(cursor.getColumnIndex(RtResourceEntityDao.Properties.ShortVideo.columnName));
        String pics = cursor.getString(cursor.getColumnIndex(RtResourceEntityDao.Properties.Pics.columnName));
        String thumbnails = cursor.getString(cursor.getColumnIndex(RtResourceEntityDao.Properties.Thumbnails.columnName));
        String orgpicname = cursor.getString(cursor.getColumnIndex(RtResourceEntityDao.Properties.Orgpicname.columnName));
        String audios = cursor.getString(cursor.getColumnIndex(RtResourceEntityDao.Properties.Audios.columnName));

        String time = DateUtils.translateDateTime(createDate);
        holder.timeView.setText(time);

        LogUtils.d(TAG, "[" + resourceId + "," + accountId + "," + title + "," + shortVideo + "]");

        fillAccount(holder, accountId);
        final String firstPic = fillImage(holder, pics, thumbnails, orgpicname);

        showVideo(holder, shortVideo, title, pics);

        holder.contentView.setText(title);
        holder.contentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, RtNoteListActivity.class);
                intent.putExtra(LocalConstants.BIND_RESOURCE_ID, resourceId);
                mContext.startActivity(intent);
            }
        });
        holder.discussIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, RtNoteListActivity.class);
                intent.putExtra(LocalConstants.BIND_RESOURCE_ID, resourceId);
                mContext.startActivity(intent);
            }
        });


        holder.shareIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShareUtils.doShareResource(resourceId, firstPic, title, null, null);
            }
        });
        holder.actionIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                com.orhanobut.dialogplus.ViewHolder holder;
                if (accountId.equals(AccountUtils.getAccountID())) {
                    holder = new com.orhanobut.dialogplus.ViewHolder(
                            R.layout.pop_menu_delete);
                } else {
                    holder = new com.orhanobut.dialogplus.ViewHolder(
                            R.layout.pop_menu_blacklist);
                }
                final DialogPlus dialog = DialogPlus.newDialog(mContext)
                        .setContentHolder(holder)
                        .setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(DialogPlus dialog, View view) {
                                if (view.getId() == R.id.act_delete) {
                                    doDelete(resourceId);
                                    dialog.dismiss();
                                } else if (view.getId() == R.id.act_cancel) {
                                    dialog.dismiss();
                                } else if (view.getId() == R.id.act_add_blacklist) {
                                    doAddBlacklist(accountId);
                                    dialog.dismiss();
                                }
                            }
                        })
                        .setCancelable(true)
                        .create();
                dialog.show();
            }
        });
    }

    private void fillAccount(ViewHolder viewHolder, final String accountId) {
        String avatar = null;
        String nickname = null;
        boolean needFetch = true;
        EaseUser2 friend = FriendHelper.getInstance().getContactUser(accountId);
        if (friend != null) {
            avatar = friend.getAvatar();
            nickname = friend.getUsername().equals("") ? friend.getNick() : friend.getUsername();
            needFetch = false;
        } else {
            // 非好友
            TrendMember member = PersistUtils.getTrendMember(accountId);
            if (member != null) {
                avatar = member.getAvatarUrl();
                nickname = member.getNickname();
                needFetch = false;
            }
        }
        if (!needFetch) {
            Picasso.with(GlobalContext.getGlobalContext()).load(avatar).fit()
                    .placeholder(R.drawable.default_head)
                    .centerInside().into(viewHolder.avatarView);
            viewHolder.nicknameView.setText(nickname);
        } else {
            UserNetworkHelper.getInstance().getUserInfo(accountId, viewHolder.avatarView, viewHolder.nicknameView);
        }
        viewHolder.avatarView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RtGeneralHelper.showUser(mContext, accountId);
            }
        });
        viewHolder.nicknameView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RtGeneralHelper.showUser(mContext, accountId);
            }
        });
    }

    /**
     * return first pic
     *
     * @param viewHolder
     * @param pics
     * @param thumbnails
     * @param orgpicname
     * @return
     */
    private String fillImage(ViewHolder viewHolder, String pics, String thumbnails, String orgpicname) {
        String firstPic = null;
        final ArrayList<String> bigPics = new ArrayList<String>();
        if (!TextUtils.isEmpty(pics)) {
            String[] picUrls = TextUtils.split(pics, ",");
            for (int i = 0; i < picUrls.length; i++) {
                bigPics.add(picUrls[i]);
            }
            if (!bigPics.isEmpty()) {
                firstPic = bigPics.get(0);
            }
        }
        if (!TextUtils.isEmpty(thumbnails) && !TextUtils.isEmpty(orgpicname)) {
            String[] thumbs = TextUtils.split(thumbnails, ",");
            List<ImageModel> imageModels = new ArrayList<ImageModel>();
            if (thumbs.length == 1) {
                int point = orgpicname.indexOf(".");
                String name = point > -1 ? orgpicname.substring(0, point) : orgpicname;
                if (name.matches("(\\d+)x(\\d+)")) {
                    int x = name.indexOf("x");
                    String width = name.substring(0, x);
                    String height = name.substring(x + 1);
                    imageModels.add(new ImageModel().setUrl(thumbs[0])
                            .setWidth(Integer.valueOf(width))
                            .setHeight(Integer.valueOf(height)));
                } else {
                    imageModels.add(new ImageModel().setUrl(thumbs[0]));
                }
            } else {
                for (int i = 0; i < thumbs.length; i++) {
                    imageModels.add(new ImageModel().setUrl(thumbs[i]));
                }
            }

            RtResourceGalleryAdapter galleryAdapter = new RtResourceGalleryAdapter(mContext, imageModels);
            viewHolder.galleryView.setAdapter(galleryAdapter);

            viewHolder.galleryView.setOnItemClickListerner(new NineGridlayout.OnItemClickListerner() {
                @Override
                public void onItemClick(View view, int position) {
                    RtGeneralHelper.showPicture(mContext, position, bigPics);
                }
            });

            viewHolder.galleryView.setVisibility(View.VISIBLE);
        } else {
            viewHolder.galleryView.setVisibility(View.GONE);
        }
        return firstPic;
    }

    private void showVideo(final ViewHolder viewHolder, final String video, String title, final String thumb) {
        if (!TextUtils.isEmpty(video)) {
            viewHolder.videoPlayerView.setVisibility(View.VISIBLE);
            if (!TextUtils.isEmpty(thumb)) {
                Picasso.with(GlobalContext.getGlobalContext()).load(thumb).fit().centerInside().into(viewHolder.videoCoverView);
                Picasso.with(GlobalContext.getGlobalContext()).load(thumb).fit().centerInside().into(viewHolder.videoView.ivThumb);
            }

            if (!viewHolder.isInited) {
                viewHolder.videoView.release();
                viewHolder.videoView.setUp(video, title, false);
                viewHolder.videoView.setTag(video);
                viewHolder.isInited = true;
            }
        } else {
            viewHolder.videoPlayerView.setVisibility(View.GONE);
        }
    }

    private void doDelete(final String resourceId) {
        RtDelResourceRequest req = new RtDelResourceRequest(AccountUtils.getAccountID(), resourceId);
        RestClient.getRestNormalService().rtDeleteResource(req, new Callback<RtDelResourceResponse>() {
            @Override
            public void success(RtDelResourceResponse delResp, Response response) {
                if (response.getStatus() == 200) {
                    if (delResp.errorCode.equals("0")) {
                        PersistUtils.deleteRtResource(resourceId);
                        EventBus.getDefault().post(new RtResourceRefreshEvent(RtResourceRefreshEvent.Mode.DELETE));
                    }
                }
            }

            @Override
            public void failure(RetrofitError error) {
                L.e("doDelete()", error);
            }
        });
    }

    private void doAddBlacklist(String accountId) {
        RtBlacklistRequest request = new RtBlacklistRequest(accountId);
        RestClient.getRestNormalService().rtAddBlacklist(AccountUtils.getAccountID(), request,
                new Callback<RtBlacklistResponse>() {
                    @Override
                    public void success(RtBlacklistResponse resp, Response response) {
                        if (resp.data == null) {
                            return;
                        }
                        List<RtBlacklistEntity> entities = new ArrayList<RtBlacklistEntity>();
                        for (String accountId : resp.data) {
                            RtBlacklistEntity entity = new RtBlacklistEntity();
                            entity.setBlockUser(accountId);
                            entities.add(entity);
                        }
                        PersistUtils.saveRtBlacklist(entities);
                    }

                    @Override
                    public void failure(RetrofitError error) {
                        L.e("doAddBlacklist()", error);
                    }
                });
    }

    public void playVideo(String url, String title) {
        Intent videoPlaybackActivity = new Intent(mContext, VideoPlayActivity.class);
        videoPlaybackActivity.putExtra("fileRes", url);
        videoPlaybackActivity.putExtra("title", title);
        mContext.startActivity(videoPlaybackActivity);
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        CircleImageView avatarView;
        TextView nicknameView;
        ImageView voiceView;
        ImageView discussIcon;
        ImageView actionIcon;
        ImageView shareIcon;

        TextView timeView;
        TextView contentView;
        NineGridlayout galleryView;

        RelativeLayout videoPlayerView;
        ImageView videoCoverView;
        fm.jiecao.jcvideoplayer_lib.JCVideoPlayer videoView;
        //com.universalvideoview.UniversalMediaController videoController;

        boolean isInited;

        public ViewHolder(View itemView) {
            super(itemView);

            avatarView = (CircleImageView) itemView.findViewById(R.id.avatar);
            nicknameView = (TextView) itemView.findViewById(R.id.nickname);
            voiceView = (ImageView) itemView.findViewById(R.id.item_voice);
            discussIcon = (ImageView) itemView.findViewById(R.id.item_discuss_icon);
            actionIcon = (ImageView) itemView.findViewById(R.id.item_action);
            shareIcon = (ImageView) itemView.findViewById(R.id.item_share_icon);
            timeView = (TextView) itemView.findViewById(R.id.item_time);
            contentView = (TextView) itemView.findViewById(R.id.item_content);
            galleryView = (NineGridlayout) itemView.findViewById(R.id.item_gallery);

            videoPlayerView = (RelativeLayout) itemView.findViewById(R.id.video_player);
            videoCoverView = (ImageView) itemView.findViewById(R.id.video_cover);
            videoView = (fm.jiecao.jcvideoplayer_lib.JCVideoPlayer) itemView.findViewById(R.id.video_view);
            //videoController = (com.universalvideoview.UniversalMediaController) itemView.findViewById(R.id.video_controller);

            voiceView.setVisibility(View.GONE);
        }

    }
}
